package com.example.demo.demos.replaceKey;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import static com.example.demo.demos.replaceKey.ReadExcel.excelKey;


/**
 * @Author: lixz
 * @Date: 2024/07/24/16:26
 */
public class ReplaceKey {

    //excel 新旧字段映射map

    public static void main(String[] args) {
        try {
            toMap();
            //对比字段key
            String keys = "name";
            replaceKey(keys);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void toMap() throws Exception {
        String userPath = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath();
        File file = new File(userPath + "\\数据库对照.xlsm");
        ReadExcel.getInputStream(file);
    }

    public static void replaceKey(String keys) throws IOException {
        //excel
        String userPath = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath();

        File outFile = new File(userPath + "\\新文件.docx");
        boolean newFile = outFile.createNewFile();
        if (!newFile) {
            return;
        }

        File file2 = new File(userPath + "\\data.docx");
        InputStream is2 = Files.newInputStream(Paths.get(file2.getCanonicalPath()));
        XWPFDocument document = new XWPFDocument(is2);
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            String rowStr = paragraph.getText();
            for (String key : keys.split(",")) {
                int index = rowStr.indexOf(key);
                if (index == -1) {
                    continue;
                }

                String oldStr = rowStr.substring(rowStr.indexOf(":") + 3, rowStr.indexOf(",") - 1);
                if (StringUtils.isBlank(oldStr)) {
                    continue;
                }
                paragraph.removeRun(0);
                XWPFRun run = paragraph.createRun();
                if (!excelKey.containsKey(oldStr)) {
                    run.setText(rowStr + "   //todo");
                    continue;
                }
                run.setText(rowStr.replace(oldStr, String.valueOf(excelKey.get(oldStr))));
                System.out.println(excelKey.get(oldStr));
                break;
            }
        }

        FileOutputStream out = new FileOutputStream(outFile);
        document.write(out);
    }
}
